package com.qiaofang.housewarehouse.facade.globalexception.handler;


import javax.servlet.http.HttpServletRequest;

import com.qiaofang.housewarehouse.base.exceptions.UserCenterExcption;
import com.qiaofang.housewarehouse.stub.constants.ResponseCode;
import com.qiaofang.housewarehouse.stub.response.CommonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.annotation.RestController;


/**
 * 全局异常处理器
 * @author Administrator
 *
 */
@RestController
@ControllerAdvice
public class HouseWareHouseGlobalExceptionHandler {
	private static final Logger LOGGER = LoggerFactory.getLogger(HouseWareHouseGlobalExceptionHandler.class);

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public Object defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
		CommonResponse response = new CommonResponse();
		if(e instanceof UserCenterExcption){
			response.setResponseCode(((UserCenterExcption) e).getErrorCode());
			response.setResponseMessage(e.getMessage());
		}if(e instanceof MethodArgumentNotValidException){
			response.setResponseCode(ResponseCode.RC_PARAMETER_ERROR.getResponseCode());
			response.setResponseMessage(e.getMessage());
			LOGGER.error("请求参数不合法",e);
		}else{
			response.setResponseCode(ResponseCode.RC_EXCEPTION_ERROR.getResponseCode());
			response.setResponseMessage(ResponseCode.RC_EXCEPTION_ERROR.getResponseMessage());
			LOGGER.error("未知异常",e);
		}
		return response;
	}
}
